using AutoMapper;
using BaseData.WriteApi.Appcontext.Command.DescendantFiles;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SmartTracking.Domain.HQX;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace BaseData.WriteApi.Appcontext.CommandHandler.DescendantFiles
{
    /// <summary>
    /// 后裔档案创建命令处理器
    /// </summary>
    public class CreateDescendantFileCommandHandler : IRequestHandler<CreateDescendantFileCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<DescendantFile> _descendantRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<CreateDescendantFileCommandHandler> _logger;

        public CreateDescendantFileCommandHandler(
            IBaseRepository<DescendantFile> descendantRepository,
            IMapper mapper,
            ILogger<CreateDescendantFileCommandHandler> logger)
        {
            _descendantRepository = descendantRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理后裔档案创建命令
        /// </summary>
        /// <param name="request">后裔档案创建命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>创建结果</returns>
        public async Task<ApiResult<int>> Handle(CreateDescendantFileCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证请求参数
                if (request == null)
                {
                    _logger.LogWarning("后裔档案创建请求参数为空");
                    return new ApiResult<int> { Code = ApiEnum.新增失败, Message = "请求参数不能为空", data = 0 };
                }

                // 验证数据
                if (!request.Validate(out string errorMessage))
                {
                    _logger.LogWarning($"后裔档案创建数据验证失败: {errorMessage}");
                    return new ApiResult<int> { Code = ApiEnum.新增失败, Message = errorMessage, data = 0 };
                }

                // 检查耳号是否已存在
                var existingDescendant = await _descendantRepository.GetAll().FirstOrDefaultAsync(d => d.EarSignal == request.EarSignal && !d.IsDeleted);
                if (existingDescendant != null)
                {
                    _logger.LogWarning($"耳号 {request.EarSignal} 已存在");
                    return new ApiResult<int> { Code = ApiEnum.新增失败, Message = "该耳号已存在", data = 0 };
                }

                // 创建后裔档案实体
                var descendantFile = new DescendantFile
                {
                    EarSignal = request.EarSignal,
                    ElectronicEarTag = request.ElectronicEarTag,
                    FatherNumber = request.FatherNumber,
                    MotherEarTag = request.MotherEarTag,
                    Variety = request.Variety,
                    Gender = request.Gender,
                    BirthStatus = request.BirthStatus,
                    DateofBirth = request.DateofBirth,
                    EntryDate = request.EntryDate,
                    PlaceOfBirth = request.PlaceOfBirth,
                    BirthWeight = request.BirthWeight,
                    GeneRank = request.GeneRank,
                    Note = request.Note,
                    IsDeleted = false
                };

                // 执行插入操作
                var result = await _descendantRepository.AddAsync(descendantFile);

                if (result > 0)
                {
                    _logger.LogInformation($"成功创建后裔档案，ID: {result}, 耳号: {request.EarSignal}");
                    return new ApiResult<int> { Code = ApiEnum.新增成功, Message = "后裔档案创建成功", data = result };
                }
                else
                {
                    _logger.LogError($"创建后裔档案失败，耳号: {request.EarSignal}");
                    return new ApiResult<int> { Code = ApiEnum.新增失败, Message = "后裔档案创建失败", data = 0 };
                }
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning($"参数验证异常: {ex.Message}");
                return new ApiResult<int> { Code = ApiEnum.新增失败, Message = ex.Message, data = 0 };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"创建后裔档案时发生系统异常: {ex.Message}");
                return new ApiResult<int> { Code = ApiEnum.新增失败, Message = "系统异常，请联系管理员", data = 0 };
            }
        }
    }
}